package com.guigu.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guigu.common.utils.R;
import com.guigu.eduservice.entity.Order;
import com.guigu.eduservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 订单表（存储买卖双方的交易订单信息） 前端控制器
 * </p>
 *
 * @author Xiaosong
 * @since 2025-10-01
 */
@RestController
@RequestMapping("/advertisement")
public class OrderController {
    @Autowired
    private OrderService orderService;
    //查询最新成交案例
    @GetMapping("addOrder")
    public R addOrder(){
        List<Order> list = orderService.selectFourAdvertisement() ;
        return R.ok().data("list",list);
    }
    //根据id查询
    @GetMapping("/{id}")
    public R getOrder(@PathVariable Long  id){
        Order order = orderService.getOrder(id);
        return R.ok().data("order",order);
    }
    //生成订单
    @PostMapping("addOrdd")
    public R addOrdd(@RequestBody Order order){
        //设置订单编号
        order.setOrderId(System.currentTimeMillis());
        System.out.println(order);
        QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("equipment_id",order.getEquipmentId());
        orderService.remove(queryWrapper1);
        boolean save = orderService.save(order);
        //根据设备id和用户id,卖家id查询主键
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_id",order.getBuyerId());
        queryWrapper.eq("seller_id",order.getSellerId());
        queryWrapper.eq("equipment_id",order.getEquipmentId());
        queryWrapper.eq("order_status",0);
        Order one = orderService.getOne(queryWrapper);
        return R.ok().data("orderId",one.getOrderId());
    }

     //付定金更改订单状态
    @PutMapping ("/updateOrder/{orderId}")
    public R updateOrder(@PathVariable Long orderId){
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.set("order_status", 2)
                .eq("order_id", orderId)
                .eq("order_status", 1);
        boolean update = orderService.update(wrapper);
        return update ? R.ok() : R.error();
    }
}
